#include<sys/types.h>
#include<unistd.h>
#include<sys/file.h>
#include<stdio.h>
#include<string.h>
char read_buf[4];
char write_buf[4];
int pipe_fd[2];
pid_t pid1,pid2,pid3,pid4;
int producer(int id);
int consumer(int id);
int main()
{
if(pipe(pipe_fd)<0)
{
  printf("pipe create error\n");
   
}
else
{
  printf("pipe is created successfully\n");
     if((pid1=fork())==0)
       producer(1);
	  if((pid2=fork())==0)
		 producer(2);
     if((pid3=fork())==0)
      consumer(1);
	  if((pid4=fork())==0)
		 consumer(2);
 }
close(pipe_fd[0]);
close(pipe_fd[1]);
return 0;
}

int producer(int id)
{
    printf("producer %d is running!\n",id);
    close(pipe_fd[0]);
    int i;
    for(i=0;i<2;i++)
           {
        sleep(3);
        if(id==1)
           strcpy(write_buf,"aaa\0");
        else
           strcpy(write_buf,"bbb\0");
        if(write(pipe_fd[1],write_buf,4)==-1)
           printf("write to pipe error\n");
             }
     close(pipe_fd[1]);  
     printf("producer %d is over!\n",id);
     return id;
}
int consumer(int id)
{
    printf("consumer %d is running!\n",id);
    close(pipe_fd[1]);
    if(id==1)
      strcpy(write_buf,"ccc\0");
    else
      strcpy(write_buf,"ddd\0");
    while(1)
           {
      sleep(1);
      strcpy(read_buf,"eee\0");
	   if(read(pipe_fd[0],read_buf,4)==0)
   		break;
		printf("consumer %d get %s,while the write_buf is %s\n",id,read_buf,write_buf);
            }
     close(pipe_fd[0]);
	  printf("consumer %d is over!\n",id);
     return id;
               

}
